package com.shinhye.smartsms;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shinhye.smartsms.utils.MyAsyncQueryHandler;
import com.shinhye.smartsms.utils.SmsUris;

public class GroupActivity extends ListActivity implements OnItemLongClickListener, OnItemClickListener{

	private MyCursorAdapter adapter;
	private MyAsyncQueryHandler asyncQueryHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ListView lv_group_main = getListView();
		adapter = new MyCursorAdapter(this, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		lv_group_main.setAdapter(adapter);
		lv_group_main.setOnItemLongClickListener(this);
		lv_group_main.setOnItemClickListener(this);
		
		asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());
		getData();
	}
	
	private void getData() {
		asyncQueryHandler.startQuery(911, adapter, SmsUris.GROUP_URI, new String[]{"_id", "name"}, null, null, null);
	}

	class MyCursorAdapter extends CursorAdapter{
		public MyCursorAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
		}

		@Override
		protected void onContentChanged() {
			getData();
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = View.inflate(GroupActivity.this, R.layout.item_group_main, null);
			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
			String text = cursor.getString(1);
			System.out.println("group_name::" + text);
			tv_name.setText(text);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		showCreateGroupDialog();
		return super.onOptionsItemSelected(item);
	}

	private void showCreateGroupDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("新建群组");
		View view = View.inflate(this, R.layout.dialog_newgroup, null);
		
		Button btn_newgroup = (Button) view.findViewById(R.id.btn_newgroup);
		final EditText et_group_name = (EditText) view.findViewById(R.id.et_group_name);
		
		final AlertDialog dialog = builder.create();
		dialog.setView(view, 0, 0, 0, 0);
		dialog.show();
		
		btn_newgroup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = et_group_name.getText().toString().trim();
				if(TextUtils.isEmpty(name)) {
					Toast.makeText(GroupActivity.this, "群组名不能为空！", Toast.LENGTH_SHORT).show();
				} else {
					addGroup(name);
					dialog.dismiss();
				}
			}
			
		});
	}
	
	private void addGroup(String name) {
		Cursor cursor = getContentResolver().query(SmsUris.GROUP_URI, null, "name = ?", new String[]{name}, null);
		if(cursor.moveToNext()) {
			Toast.makeText(this, "该群组已经存在！", Toast.LENGTH_SHORT).show();
			return;
		}
		ContentValues cv = new ContentValues();
		cv.put("name", name);
		Uri resUri = getContentResolver().insert(SmsUris.GROUP_URI, cv);
		long id;
		if((id = ContentUris.parseId(resUri)) == -1) {
			System.out.println("创建失败！");
		} else {
			System.out.println("添加成功，位于第" + id + "行");
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		Cursor cursor = (Cursor) adapter.getItem(position);
		showOperaDialog(cursor.getInt(0));
		return true;
	}

	private void showOperaDialog(final int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(new String[]{"修改", "删除"}, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which) {
				case 0:
					showUpdateDialog(id);
					break;
				case 1:
					showDeleteDialog(id);
					break;
				}
			}
		});
		
		builder.show();
	}
	
	private void showUpdateDialog(final int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("修改群组名");
		View view = View.inflate(this, R.layout.dialog_newgroup, null);
		
		Button btn_newgroup = (Button) view.findViewById(R.id.btn_newgroup);
		btn_newgroup.setText("确定修改");
		final EditText et_group_name = (EditText) view.findViewById(R.id.et_group_name);
		
		final AlertDialog dialog = builder.create();
		dialog.setView(view, 0, 0, 0, 0);
		dialog.show();
		
		btn_newgroup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = et_group_name.getText().toString().trim();
				if(TextUtils.isEmpty(name)) {
					Toast.makeText(GroupActivity.this, "群组名不能为空！", Toast.LENGTH_SHORT).show();
				} else {
					updateGroup(name, id);
					dialog.dismiss();
				}
			}

		});
		
	}
	
	private void updateGroup(String name, int id) {
		ContentValues cv = new ContentValues();
		cv.put("name", name);
		getContentResolver().update(SmsUris.GROUP_URI, cv, "_id=?", new String[]{id + ""});
	}
	
	protected void showDeleteDialog(final int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("删除群组");
		builder.setMessage("您确定要删除该组吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				deleteGroup(id);
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	protected void deleteGroup(int id) {
		Uri uri = ContentUris.withAppendedId(SmsUris.GROUP_URI, id);
		getContentResolver().delete(uri, null, null);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Cursor cursor = (Cursor) adapter.getItem(position);
		int _id = cursor.getInt(0);
		Cursor resCursor = getContentResolver().query(SmsUris.THREAD_URI, new String[]{"thread_id"}, "group_id=?", new String[]{_id + ""}, null);
		if(resCursor.getCount() == 0){
			Toast.makeText(this, "该群组下没有任何会话", Toast.LENGTH_SHORT).show();
			return;
		}
		int[] threadIds = new int[resCursor.getCount()];
		while(resCursor.moveToNext()) {
			threadIds[resCursor.getPosition()] = resCursor.getInt(0);
		}
		Intent intent = new Intent(this, ConversationActivity.class);
		intent.putExtra("threadIds", threadIds);
		startActivity(intent);
	}
}
